<template>
  <div class="currency-box">
    <div class="left">
      <!-- 工单列表的搜索 Start -->
      <header>
        <div class="search">
          <a-input
            placeholder="输入单号"
            v-model="searchInfo.keyWords"
            @keyup.enter="upList"
          />
        </div>
        <div class="icon">
          <a-popover
            placement="bottom"
            trigger="click"
            v-model="visible"
            title="筛选"
          >
            <template slot="content">
              <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-form-model-item label="填写时间">
                  <a-range-picker
                    @change="onTimeChange"
                    :defaultValue="defaultdateList"
                  />
                </a-form-model-item>
                <a-form-model-item label="厂区">
                  <a-select
                    :allowClear="true"
                    mode="multiple"
                    :maxTagCount="1"
                    class="selectwidth"
                    v-model="searchInfo.WSType"
                    placeholder="请选择"
                    @change="handleChange"
                  >
                    <a-select-option
                      v-for="item in WSTypeList"
                      :key="item.type"
                      :value="item.type"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="车间">
                  <a-select
                    :allowClear="true"
                    class="selectwidth"
                    mode="multiple"
                    v-model="searchInfo.SegmentIDs"
                    placeholder="请选择"
                  >
                    <a-select-option
                      v-for="item in QSegmentList"
                      :key="item.type"
                      :value="item.type"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
                </a-form-model-item>

                <a-form-model-item label="计划单号">
                  <a-input v-model="searchInfo.packingPlanNo" />
                </a-form-model-item>
                <a-form-model-item label="生产批号">
                  <a-input v-model="searchInfo.batchNo" />
                </a-form-model-item>
                <a-form-model-item label="产品编码">
                  <a-input v-model="searchInfo.materialCode" />
                </a-form-model-item>

                <a-form-model-item label="状态">
                  <a-select
                    style="width: 100%"
                    v-model="jobRecordStatusData"
                    mode="multiple"
                    :maxTagCount="1"
                  >
                    <a-select-option
                      :value="item.num"
                      v-for="item in jobRecordStatusList"
                      :key="item.num"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="打印状态">
                  <a-select
                    v-model="searchInfo.printStatus"
                    placeholder="打印状态"
                  >
                    <a-select-option value="0">全部</a-select-option>
                    <a-select-option value="1">已打印</a-select-option>
                    <a-select-option value="-1">未打印</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="是否作废">
                  <a-select
                    v-model="searchInfo.IsInvaliDateStatus"
                    placeholder="是否作废"
                  >
                    <a-select-option value="0">全部</a-select-option>
                    <a-select-option value="1">正常</a-select-option>
                    <a-select-option value="-1">作废</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item
                  style="display: flex; justify-content: flex-end"
                >
                  <a-button class="default-button" @click="upList">
                    查询
                  </a-button>
                </a-form-model-item>
              </a-form-model>

              <!-- <div style="display: flex; justify-content: flex-end;">
                                
                            </div> -->
            </template>
            <a-icon type="filter" class="icon-class" />
          </a-popover>
        </div>
      </header>
      <!-- 工单列表的搜索 End -->
      <!-- 工单列表的展示 Start -->
      <section
        v-if="list.length == 0"
        style="position: relative; top: 50%; left: 25%"
      >
        <img src="@/assets/svg/none-list.svg" alt="" />
      </section>

      <section
        v-else
        infinite-scroll-immediate-check="false"
        infinite-scroll-listen-for-event="false"
        v-infinite-scroll="handleinfiniteOnLoad"
        infinite-scroll-disabled="busy"
        infinite-scroll-distance="20"
      >
        <div
          :class="[
            'section-box',
            index == currentIndex ? 'section-active' : '',
          ]"
          v-for="(item, index) in list"
          :key="index"
          @click="checkPacking(item, index)"
        >
          <div class="section-box-info">
            <p class="dimension-text">
              计划单号:{{ item.PackingPlanNo || "/" }}
            </p>
            <p class="dimension-text">
              产品编码:{{ item.MaterialCode || "/" }}
            </p>
            <p class="dimension-text">
              产品名称:{{ item.MaterialName || "/" }}
            </p>
            <p>单据类型:{{ mateFind(item.OrderType).name || "/" }}</p>
            <!-- <p>生产批号:{{ item.BatchNo || "/" }}</p> -->
            <p>厂区:{{ item.WSName || "/" }}</p>
            <p>车间:{{ item.SegmentName || "/" }}</p>
            <p>状态:{{ item.JobRecordStatusStr || "/" }}</p>
          </div>
        </div>
      </section>

      <!-- 工单列表的展示 End -->
    </div>
    <a-spin
      :spinning="loading"
      tip="加载中..."
      size="large"
      class="right batch-printing-right"
    >
      <div class="spin-box-div">
        <div class="header-title">
          <div
            style="
              margin: 5px;
              display: flex;
              align-content: center;
              align-items: center;
              width: 100px;
            "
          >
            <a-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
            >
              全选
            </a-checkbox>
          </div>
          <div style="margin: 5px">
            生产批号：
            <a-input
              placeholder="输入生产批号"
              v-model="batchNoFilter"
              style="width: 200px"
            />
          </div>
          <div style="margin: 5px">
            打印状态：
            <a-select
              v-model="printStatusFilter"
              style="width: 120px"
              placeholder="打印状态"
            >
              <a-select-option value="0">全部</a-select-option>
              <a-select-option value="1">已打印</a-select-option>
              <a-select-option value="-1">未打印</a-select-option>
            </a-select>
          </div>
          <div style="margin: 5px">
            是否作废
            <a-select
              v-model="isInvaliDateFilter"
              style="width: 120px"
              placeholder="是否作废"
            >
              <a-select-option value="0">全部</a-select-option>
              <a-select-option value="1">正常</a-select-option>
              <a-select-option value="-1">作废</a-select-option>
            </a-select>
          </div>
          <div style="margin: 5px">
            <general-button
              class="default-button"
              size="small"
              @operation="batchExamine"
              :btnDisabled="!batchList.find((item) => item.isCheckBox)"
              :loading="startPrint"
              btnText="一键审核"
              btnPowerNum="B9D32091-8BEA-4344-BC4B-A876E890A9D8"
            >
            </general-button>
          </div>
          <div style="margin: 5px">
            <general-button
              class="default-button"
              size="small"
              @operation="mergeFun"
              :btnDisabled="!batchList.find((item) => item.isCheckBox)"
              :loading="startPrint"
              btnText="一键打印"
              btnPowerNum="DCBC94F0-607E-46E1-8D05-1E343BC75EEC"
            >
            </general-button>
          </div>
          <div style="margin: 5px">
            <general-button
              class="default-button"
              size="small"
              @operation="mergePrintFun"
              :btnDisabled="!batchList.find((item) => item.isCheckBox)"
              :loading="startPrint"
              btnText="合并打印"
              btnPowerNum="DCBC94F0-607E-46E1-8D05-1E343BC75EEC"
            >
            </general-button>
          </div>
          <div style="margin: 5px">
            <a-button type="link" @click="toggleExpandAll">
              {{ isAllExpanded ? "全部收起" : "全部展开" }}
            </a-button>
          </div>
        </div>
        <!-- 选择该工单的批记录 Start -->
        <header>
          <div class="batch-left">
            <div
              class="type-list-box"
              style="height: 100%"
              v-show="batchList.length == 0"
            >
              <div class="info-box">
                <span>暂无绑定项</span>
              </div>
            </div>

            <div
              v-for="(itm, idx) in filteredBatchList"
              :key="idx"
              :class="['type-list-box', idx == mateIdx ? 'active' : '']"
            >
              <div
                v-if="itm.JobRecordStatus === 13 && !itm.IsInvaliDate"
                class="watermark"
                style="color: #04d76a"
              >
                已审核
              </div>
              <div
                v-if="itm.UnModifyDt && !itm.IsInvaliDate"
                class="watermark"
                style="color: #ff6c13"
              >
                已弃审
              </div>
              <div
                v-if="itm.IsInvaliDate"
                class="watermark"
                style="color: #b9000a"
              >
                已作废
              </div>
              <article class="article-list-box">
                <div
                  :style="{ maxHeight: isAllExpanded ? '500px' : '28px' }"
                  class="article-top"
                  @click="checkBatch(itm, idx)"
                >
                  <div class="info-box-handle">
                    <a-checkbox
                      v-model="itm.isCheckBox"
                      @change.stop="checkChange"
                      @click.stop
                      style="width: 30px"
                    ></a-checkbox>
                    <div>
                      <span style="margin-left: 10px">工作集：</span
                      ><span>{{
                        itm.JobGroupName + "(" + itm.JobTempletVisionOut + ")"
                      }}</span>
                    </div>
                    <div>
                      <span style="margin-left: 10px">生产批号：</span
                      ><span>{{ itm.BatchNo }}</span>
                    </div>
                    <div>
                      <span style="margin-left: 10px">创建人：</span
                      ><span>{{ itm.CreateUserName }}</span>
                    </div>
                    <div>
                      <span style="margin-left: 10px">创建时间：</span
                      ><span>{{ dateExt.showFullDate(itm.CreateDt) }}</span>
                    </div>
                    <div>
                      <span style="margin-left: 10px">打印次数：</span
                      ><span>{{ itm.PrintIndex }}</span>
                    </div>
                    <div>
                      <span style="margin-left: 10px">状态：</span
                      ><span>{{ getVerifyStatus(itm.JobRecordStatus) }}</span>
                    </div>
                    <div>
                      <span style="margin-left: 10px">审核人：</span
                      ><span>{{ itm.VerifyUserName }}</span>
                    </div>
                    <div>
                      <span style="margin-left: 10px">审核时间：</span
                      ><span>{{ dateExt.showFullDate(itm.VerifyDt) }}</span>
                    </div>
                  </div>
                </div>
                <div class="info-box">
                  <span>操作：</span>
                  <span>
                    <general-button
                      class="default-button"
                      style="margin-left: 5px"
                      size="small"
                      @operation="onPrint(itm)"
                      :btnDisabled="idx != mateIdx"
                      :loading="startPrint"
                      btnText="打印"
                      btnPowerNum="DCBC94F0-607E-46E1-8D05-1E343BC75EEC"
                    >
                    </general-button>
                    <general-button
                      style="margin-left: 5px"
                      class="default-button"
                      size="small"
                      @operation="onAppointPrint"
                      :btnDisabled="idx != mateIdx"
                      :loading="startPrint"
                      btnText="指定打印"
                      btnPowerNum="DCBC94F0-607E-46E1-8D05-1E343BC75EEC"
                    >
                    </general-button>
                    <general-button
                      style="margin-left: 5px"
                      class="default-button"
                      size="small"
                      @operation="onExamine(itm, true)"
                      btnPowerNum="CE4FD723-1A8C-4DC2-B45E-95F12F0FD01A"
                      :btnDisabled="idx != mateIdx"
                      btnText="强制审核"
                    >
                    </general-button>
                    <general-button
                      style="margin-left: 5px"
                      class="default-button"
                      size="small"
                      @operation="onExamine(itm, false)"
                      btnPowerNum="B9D32091-8BEA-4344-BC4B-A876E890A9D8"
                      :btnDisabled="idx != mateIdx"
                      btnText="审核"
                    >
                    </general-button>
                    <general-button
                      style="margin-left: 5px"
                      class="default-button"
                      size="small"
                      @operation="onUnExamine(itm)"
                      btnPowerNum="B9D32091-8BEA-4344-BC4B-A876E890A9D8"
                      :btnDisabled="idx != mateIdx"
                      btnText="弃审"
                    >
                    </general-button>
                    <general-button
                      style="margin-left: 5px"
                      class="default-button"
                      size="small"
                      @operation="onInvaliDate(itm)"
                      btnPowerNum="E14318B4-DCBC-4D1F-8D99-494C19590A97"
                      :btnDisabled="idx != mateIdx"
                      btnText="作废"
                    >
                    </general-button>
                    <general-button
                      style="margin-left: 5px"
                      class="default-button"
                      size="small"
                      @operation="onUnInvaliDate(itm)"
                      btnPowerNum="3C0E41E6-CC3D-4C45-ADF2-4376CA480137"
                      :btnDisabled="idx != mateIdx"
                      btnText="还原"
                    >
                    </general-button>
                  </span>
                </div>
              </article>
            </div>
          </div>
        </header>
        <!-- 选择该工单的批记录 End -->
        <section
          v-if="
            mateCurrentInfo.JobRecordList != null &&
            mateCurrentInfo.JobRecordList.length == 0
          "
        >
          <img
            src="@/assets/svg/none-list.svg"
            alt=""
            style="position: relative; top: 50%; left: 50%"
          />
        </section>
        <section v-else style="margin: 10px 0" ref="print">
          <div
            v-for="(item, index) in mateCurrentInfo.JobRecordList"
            :key="item.JobRecordID"
          >
            <div
              :class="[
                !item.noData ? 'print-inside' : '',
                item.IsPaging ? 'print-box' : '',
              ]"
              v-if="!item.noData"
            >
              <div
                :class="item.IsPaging ? 'table-margin' : ''"
                v-if="
                  item.JobRecordDetaiList != null &&
                  item.JobRecordDetaiList.length != 0 &&
                  item.JobTempletIndex == 1
                "
              >
                <!-- 需要打印且展示的部分 Start -->
                <batch-box
                  v-if="item.TableType == 1"
                  :list="item.JobRecordDetaiList"
                  :item="item"
                  :mateCurrentInfo="item"
                ></batch-box>
                <!-- 需要打印且展示的部分 End  -->

                <!-- 聚合表单 Start -->
                <polymerize-box
                  v-if="item.TableType == 2 || item.TableType == 3"
                  :isShowBody="true"
                  :list="item.JobRecordDetaiList"
                  :item="item"
                  :headerList="item.JobRecordDetaiHList"
                  :mateCurrentInfo="item"
                ></polymerize-box>
                <!-- 聚合表单 End -->
              </div>
              <div
                v-if="
                  item.JobRecordDetaiList != null &&
                  item.JobRecordDetaiList.length != 0 &&
                  item.JobTempletIndex != 1
                "
              >
                <!-- 需要打印且展示的部分 Start -->
                <batch-box
                  v-if="item.TableType == 1"
                  :list="item.JobRecordDetaiList"
                  :item="item"
                  :lastItem="mateCurrentInfo.JobRecordList[index - 1]"
                  :mateCurrentInfo="item"
                ></batch-box>
                <!-- 需要打印且展示的部分 End  -->

                <!-- 聚合表单 Start -->
                <polymerize-box
                  :isShowBody="true"
                  v-if="item.TableType == 2 || item.TableType == 3"
                  :list="item.JobRecordDetaiList"
                  :item="item"
                  :lastItem="mateCurrentInfo.JobRecordList[index - 1]"
                  :mateCurrentInfo="item"
                  :headerList="item.JobRecordDetaiHList"
                ></polymerize-box>
                <!-- 聚合表单 End -->
              </div>
            </div>
          </div>
        </section>
      </div>
    </a-spin>

    <print-drawer
      :show="allPrintShow"
      :mateCurrentInfo="allPrintObj"
      @updateShow="updateShowFun"
    ></print-drawer>
  </div>
</template>

<script>
import {
  getJobRecordToPackingPlanID,
  getJobRecordToPacking,
  getPackingPlanListByVerify,
  getJobRecordToList,
  getJobRecordDetailList,
  getJobRecordDetails,
  getJobRecordDetailGroupList,
  getJobRecordDetailGroups,
  verifyJobRecord,
  unVerifyJobRecord,
  invaliDateJobRecord,
  unInvaliDateJobRecord,
  printJobRecord,
} from "@/api/JobRecord";
import moment from "moment";
import BatchBox from "@/views/batch-printing/children/batch-table-box.vue";
import PolymerizeBox from "@/views/batch-printing/children/polymerize-table-box.vue";

import EditBatch from "@/views/batch-printing/children/edit-batch.vue";
import GeneralButton from "@/components/be-current-btn.vue";
import polymerizeTitle from "@/common/handle-title";
import PrintDrawer from "./children/print-drawer.vue";
import { GetWorkShopTypesAll } from "@/api/WorkShopType/index";
import { GetSegments } from "@/api/NBCSegment/index";
import { debounce } from "@/common/debounce";
import { mapState } from "vuex";
export default {
  name: "BatchExamine",
  components: {
    BatchBox,
    PolymerizeBox,
    PrintDrawer,
    EditBatch,
    GeneralButton,
  },
  data() {
    return {
      loadingNum: 0, //loading的总次数
      isRequest: false, //是否可以请求
      loading: false, //加载完成
      jobRecordStatusData: [12], //当前状态
      WSTypeList: [], //厂区列表
      QSegmentList: [], //车间列表
      currentIndex: 0, //当前选中
      jobRecordStatusList: [
        { name: "未创建", num: 0 },
        { name: "已创建未填写", num: 10 },
        { name: "填写中", num: 11 },
        { name: "已填写未审核", num: 12 },
        { name: "已审核", num: 13 },
      ], //状态列表
      printVisible: false,
      visible: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      busy: true, //列表滚动
      defaultdateList: [],
      searchInfo: {
        jobRecordStatus: null,
        keyWords: "",
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 10,
        },
        startDt: "", //开始时间
        endDt: "", //结束时间
        batchNo: "", //生产批号
        WSType: [], //厂区
        SegmentID: "", //车间
        SegmentIDs: [], //车间
        packingPlanNo: "", //计划单号
        printStatus: "0", //打印状态
        IsInvaliDateStatus: "0", //是否作废
      }, //工单列表搜索参数
      list: [], //工单列表
      listNum: 0, //总条数
      listInfo: {}, //选中的列表信息
      mateInfo: [
        { name: "灌装", type: 10 },
        { name: "外包", type: 11 },
        { name: "折叠", type: 12 },
      ], //状态筛选
      mateIdx: 0, //工作集选中项
      mateCurrentInfo: {
        JobRecordList: [],
      }, //选中的工作集
      batchList: [], //工作集列表
      batchDetailList: [], //工作记录明细列表
      polyHeaderList: [], //聚合表单表头
      allPrintShow: false, //批量打印
      allPrintObj: {}, //批量打印对象
      allIsRequest: false, //判断是否加载完成
      allLoadingNum: 0, //判断第几个完成
      polyInfo: {}, //默认添加项
      polyList: [], //修改列表
      checkAll: false,
      isIndeterminate: false, //全选
      jobGroupClass: 0, //工作集类型
      // 新增筛选条件
      batchNoFilter: "",
      printStatusFilter: "0", // 打印状态筛选条件
      isInvaliDateFilter: "0", // 是否作废筛选条件

      // 新增展开状态
      isAllExpanded: true,
    };
  },

  watch: {
    visible: {
      handler(newVal, oldValue) {
        if (newVal) {
          this.searchInfo.keyWords = "";
        }
      },
      deep: true,
    },
    loadingNum: {
      //请求全部完成再可以操作方法 5- 监听总请求变量为0时表示已经全部赋值完成,可以操控
      handler(newVal) {
        if (newVal == 0) {
          this.loading = false;
        }
      },
      deep: true,
    },
    allLoadingNum: {
      //请求全部完成再可以操作方法 5- 监听总请求变量为0时表示已经全部赋值完成,可以操控
      handler(newVal) {
        if (newVal == 0) {
          this.allPrintShow = true;
          this.loading = false;
        }
      },
      deep: true,
    },
    batchNoFilter: {
      handler() {
        this.filterBatchList();
      },
      immediate: true,
    },
    printStatusFilter: {
      handler() {
        this.filterBatchList();
      },
      immediate: true,
    },
    isInvaliDateFilter: {
      handler() {
        this.filterBatchList();
      },
      immediate: true,
    },
  },
  computed: {
    ...mapState(["startPrint"]),
    // 新增筛选后的列表计算属性
    filteredBatchList() {
      return this.batchList.filter((item) => {
        // 生产批号筛选
        const batchNoMatch =
          !this.batchNoFilter ||
          (item.BatchNo && item.BatchNo.includes(this.batchNoFilter));
        // 作废筛选
        const invaliDateMatch =
          this.isInvaliDateFilter == 0 ||
          item.IsInvaliDate == (this.isInvaliDateFilter == -1 ? true : false);
        // 打印状态筛选
        let printStatusMatch = true;
        if (this.printStatusFilter === "1") {
          printStatusMatch = item.PrintIndex > 0;
        } else if (this.printStatusFilter === "-1") {
          printStatusMatch = !item.PrintIndex || item.PrintIndex === 0;
        }

        return batchNoMatch && printStatusMatch && invaliDateMatch;
      });
    },
    watermarkStyle() {
      let status = this.itm.JobRecordStatus;
      switch (status) {
        case 13:
          return { color: "#04D76A" };
        default:
          return { color: "#000" };
      }
    },
  },
  methods: {
    // 新增展开/收起方法
    toggleExpandAll() {
      this.isAllExpanded = !this.isAllExpanded;
    },
    // 新增筛选方法
    async filterBatchList() {
      // 这里可以添加其他筛选逻辑
      console.log("筛选条件:", {
        batchNo: this.batchNoFilter,
        printStatus: this.printStatusFilter,
      });

      this.filteredBatchList.forEach((item) => {
        item.isCheckBox = false; // 重置全选状态;
      });
      this.isIndeterminate = false;
      this.checkAll = false;
      if (this.filteredBatchList && this.filteredBatchList.length > 0) {
        this.mateIdx = 0;
        // 选中当前批记录
        await this.checkBatch(this.filteredBatchList[0], 0);

        this.$nextTick(() => {
          const nextCard = document.querySelectorAll(".type-list-box")[0];
          if (nextCard) {
            nextCard.click();
          }
        });
      }
    },
    /**
     * 处理全选事件的方法
     * @param {Event} e - 输入事件对象
     */
    handleCheckAllChange(e) {
      // 遍历批量操作列表，将每个项的复选框状态设置为与全选复选框相同
      this.filteredBatchList.forEach((item) => {
        item.isCheckBox = e.target.checked;
      });
      // 设置全选状态为false，以反映所有项已被选中
      this.isIndeterminate = false;
      // 添加取消全选后的状态更新
      if (!e.target.checked) {
        this.checkAll = false;
      }
    },
    /**
     * 当选择项发生变化时调用此函数来更新全选状态和不确定状态
     * 此函数没有参数
     * 返回值：无
     */
    checkChange() {
      // 计算当前批次列表中被选中的项的数量
      const checkedCount = this.filteredBatchList.filter(
        (item) => item.isCheckBox
      ).length;

      // 更新全选状态：当所有项都被选中时，全选框设为选中状态
      this.checkAll = checkedCount === this.filteredBatchList.length;

      // 更新不确定状态：当有项被选中但不是所有项都被选中时，设为不确定状态
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.filteredBatchList.length;
    },
    /** 关闭合并打印 */
    updateShowFun(value) {
      this.allPrintShow = value;
    },

    /** 等待数据加载完成 */
    waitForDataLoaded() {
      return new Promise((resolve) => {
        const check = () => {
          if (
            this.mateCurrentInfo.JobRecordList &&
            this.mateCurrentInfo.JobRecordList.every(
              (r) => r.JobRecordDetaiList
            )
          ) {
            resolve();
          } else {
            setTimeout(check, 100);
          }
        };
        check();
      });
    },

    /** 合并打印 - 修改为循环打印 */
    async mergeFun() {
      const checkedList = this.filteredBatchList.filter(
        (item) => item.isCheckBox
      );

      if (checkedList.length === 0) {
        return this.$message.error("请先选中项再操作合并打印");
      }

      try {
        this.loading = true;
        this.$store.commit("upPrintShow", true);
        // 循环处理每个选中的批记录
        for (let i = 0; i < checkedList.length; i++) {
          const item = checkedList[i];
          if (item.JobRecordStatus != 13) {
            this.$message.error(`${item.BatchNo} 未审核，请先审核再打印`);
            return;
          }
        }
        // 循环处理每个选中的批记录
        for (let i = 0; i < checkedList.length; i++) {
          const item = checkedList[i];
          // 选中当前批记录
          const idx = this.batchList.findIndex(
            (b) =>
              b.BatchNo === item.BatchNo &&
              b.JobGroupID === item.JobGroupID &&
              b.CreateDt === item.CreateDt
          );
          if (idx >= 0) {
            this.mateIdx = idx;
            await this.checkBatch(item, idx);
          }

          // 等待数据加载完成
          await this.waitForDataLoaded();
          // 等待2秒确保数据完全加载
          await new Promise((resolve) => setTimeout(resolve, 1000));
          // 打印当前批记录
          await this.printSingleRecord(item);

          // 更新打印次数
          item.PrintIndex = (item.PrintIndex || 0) + 1;
          // 自动选中并点击下一个批记录（如果不是最后一个）
          if (i < checkedList.length - 1) {
            const nextItem = checkedList[i + 1];
            const nextIdx = this.batchList.findIndex(
              (b) =>
                b.BatchNo === nextItem.BatchNo &&
                b.JobGroupID === nextItem.JobGroupID &&
                b.CreateDt === nextItem.CreateDt
            );
            if (nextIdx >= 0) {
              // 模拟点击下一个卡片
              this.$nextTick(() => {
                const nextCard =
                  document.querySelectorAll(".type-list-box")[nextIdx];
                if (nextCard) {
                  nextCard.click();
                }
              });
            }
          }
        }

        this.$message.success(`成功打印 ${checkedList.length} 条记录`);
      } catch (error) {
        this.$message.error(`打印出错: ${error.message}`);
      } finally {
        this.loading = false;
        this.$store.commit("upPrintShow", false);
      }
    },

    /** 加载批记录数据 */
    async loadBatchRecordData(item) {
      this.mateCurrentInfo = item;
      if (!item.JobRecordList) return;

      // 加载所有关联的批记录数据
      await Promise.all(
        item.JobRecordList.map(async (record) => {
          if (record.TableType == 1) {
            await this.getJobRecordDetailGroupListFun(record);
          } else {
            await this.getJobRecordDetailListFun(record);
          }
        })
      );
    },

    /** 检查所有图片是否加载完成 - 增强版 */
    checkAllImagesLoaded() {
      return new Promise((resolve) => {
        const images = Array.from(document.querySelectorAll("img"));
        let loadedCount = 0;
        let hasPending = false;

        if (images.length === 0) {
          resolve(true);
          return;
        }

        const checkImageLoad = (img) => {
          if (img.complete && img.naturalHeight !== 0) {
            loadedCount++;
          } else {
            hasPending = true;
            img.addEventListener("load", () => {
              loadedCount++;
              checkCompletion();
            });
            img.addEventListener("error", () => {
              loadedCount++; // 即使加载失败也计入
              checkCompletion();
            });
          }
          checkCompletion();
        };

        const checkCompletion = () => {
          if (loadedCount === images.length) {
            // 所有图片处理完毕，但需要额外检查是否真的渲染完成
            setTimeout(() => {
              const pendingImages = images.filter(
                (img) => !img.complete || img.naturalHeight === 0
              );
              if (pendingImages.length === 0) {
                resolve(true);
              } else {
                // 如果仍有未加载的图片，等待更长时间
                setTimeout(() => resolve(true), 1000);
              }
            }, 300);
          }
        };

        images.forEach((img) => checkImageLoad(img));

        // 防止某些图片没有触发事件
        if (!hasPending) {
          setTimeout(() => {
            if (loadedCount === images.length) {
              resolve(true);
            } else {
              setTimeout(() => resolve(true), 1500); // 最终强制继续
            }
          }, 1000);
        }
      });
    },

    /** 打印单个批记录 - 增强图片加载检查 */
    async printSingleRecord(item) {
      const printData = [
        {
          AssetsID: item.AssetsID,
          BatchNo: item.BatchNo,
          JobGroupID: item.JobGroupID,
          CreateDt: item.CreateDt,
        },
      ];

      // 调用打印API
      const res = await printJobRecord(printData);
      if (!res.Success) {
        throw new Error(res.Message || "打印API调用失败");
      }

      // 额外等待确保渲染完成
      await new Promise((resolve) => setTimeout(resolve, 2000));

      // 触发实际打印
      this.$print(this.$refs.print);

      // 确保打印完成
      await new Promise((resolve) => setTimeout(resolve, 1000));
    },
    /** 合并打印 */
    async mergePrintFun() {
      let list = this.batchList.filter((item) => item.isCheckBox);

      if (list.length == 0)
        return this.$message.error("请先选中项再操作合并打印");
      let newList = [];
      let msg = "";
      list.map((itm) => {
        if (itm.JobRecordStatus != 13) {
          msg = "选择了未审核的批记录，请先审核再操作合并打印";
          return;
        }
        const printData = [
          {
            AssetsID: itm.AssetsID,
            BatchNo: itm.BatchNo,
            JobGroupID: itm.JobGroupID,
            CreateDt: itm.CreateDt,
          },
        ];
        itm.PrintIndex = itm.PrintIndex + 1;
        // 调用打印API
        const res = printJobRecord(printData);

        newList.push(...itm.JobRecordList);
      });
      if (msg) {
        this.$message.error(msg);
        return;
      }
      this.allPrintObj.JobRecordList = newList;
      this.allLoadingNum = newList.length;
      try {
        this.loading = true;
        for (const item of newList) {
          //请求全部完成再可以操作方法 2- 将请求可控为true
          this.allIsRequest = true;
          if (this.allIsRequest) {
            if (item.TableType == 1) {
              await this.getGroupListMergeFun(item);
            } else {
              await this.getJobRecordDetailMergeFun(item);
            }
          }
        }
      } catch (error) {
        this.$message.error(error);
      } finally {
        this.loading = false;
      }
    },
    /** 单例表单的合并打印 */
    async getGroupListMergeFun(val) {
      try {
        //请求全部完成再可以操作方法 3- 先控制停止循环
        this.allIsRequest = false;
        let params = {
          JobRecordID: val.JobRecordID,
          CreateDt: val.CreateDt,
          BatchNo: val.BatchNo,
        };
        let res = await getJobRecordDetailGroups(params);

        if (!res.Success) {
          let { JobRecordList } = this.allPrintObj;
          JobRecordList.forEach((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              item.noData = true;
              item.JobRecordDetaiList = [];
              this.allIsRequest = false;
              this.allLoadingNum--;
            }
          });
          return;
        }
        let list = res.Data.sort((a, b) => a.JobItemIndex - b.JobItemIndex);
        list.forEach((item) => {
          item.JobGroup = item.JobGroup.split("。");
          item.JobRecordDetailList = item.JobRecordDetailList.sort(
            (a, b) => a.JobItemIndex - b.JobItemIndex
          );
        });

        if (this.allPrintObj) {
          if (this.allPrintObj.JobRecordList.length == 0) return;
          let { JobRecordList } = this.allPrintObj;
          JobRecordList.forEach((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              if (list.length === 0) {
                item.noData = true;
                item.JobRecordDetaiList = [];
              } else {
                item.JobRecordDetaiList = list;
              }

              this.allIsRequest = false;
              this.allLoadingNum--;
            }
          });
        }
      } catch (err) {
        if (this.allPrintObj) {
          if (this.allPrintObj.JobRecordList.length == 0) return;
          let { JobRecordList } = this.allPrintObj;
          JobRecordList.forEach((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              item.noData = true;
              item.JobRecordDetaiList = [];
              this.allIsRequest = false;
              this.allLoadingNum--;
            }
          });
        }
      }
    },

    /** 聚合表单的合并打印 */
    async getJobRecordDetailMergeFun(val) {
      try {
        this.allIsRequest = false;
        let params = {
          JobRecordID: val.JobRecordID,
          CreateDt: val.CreateDt,
          BatchNo: val.BatchNo,
        };
        let res = await getJobRecordDetails(params);

        if (!res.Success) {
          let { JobRecordList } = this.allPrintObj;
          JobRecordList.map((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              item.noData = true;
              item.JobRecordDetaiList = [];
              item.JobRecordDetaiHList = [];
              this.allIsRequest = false;
              this.allLoadingNum--;
            }
          });
          return;
        }
        let stagingHeader = res.Data.filter(
          (item) => item.JobRecordDetailIndex == 1
        );

        stagingHeader = stagingHeader.sort((a, b) => {
          return a.JobItemIndex - b.JobItemIndex;
        });
        let polyHeaderList = polymerizeTitle.handleTitleList(stagingHeader);
        /* 先根据 JobRecordDetailIndex 把每一项排序 */
        let stagingBatchDetailList = res.Data.sort((a, b) => {
          return a.JobRecordDetailIndex - b.JobRecordDetailIndex;
        });
        /* 通过 pop方法获取数组最后一位确定共几行 */
        let batchDetailNum =
          stagingBatchDetailList[stagingBatchDetailList.length - 1]
            .JobRecordDetailIndex;
        /* 定义一个空数组 */
        let detailList = [];

        /* 通过遍历获取最大值添加列表中相对应的JobRecordDetailIndex项为一行 push进detailList数组 */
        for (let index = 1; index <= batchDetailNum; index++) {
          let list = stagingBatchDetailList.filter(
            (fitm) => fitm.JobRecordDetailIndex == index
          );
          detailList.push(list);
        }

        /* 遍历结束后将子项排序后赋值 */
        let detaiArray = detailList.map((ditm) => {
          ditm.sort((a, b) => {
            return a.JobItemIndex - b.JobItemIndex;
          });
          ditm = polymerizeTitle.handleTitleList(ditm);
          return ditm;
        });

        if (this.filteredBatchList[this.mateIdx]) {
          if (this.filteredBatchList[this.mateIdx].JobRecordList.length == 0)
            return;
          let { JobRecordList } = this.allPrintObj;
          JobRecordList.map((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              if (detaiArray.length == 0) {
                item.noData = true;
              }
              item.JobRecordDetaiList = detaiArray;
              item.JobRecordDetaiHList = polyHeaderList;
              this.allIsRequest = false;
              this.allLoadingNum--;
            }
          });
        }
      } catch (err) {
        if (this.filteredBatchList[this.mateIdx]) {
          if (this.filteredBatchList[this.mateIdx].JobRecordList.length == 0)
            return;
          let { JobRecordList } = this.allPrintObj;
          JobRecordList.map((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              item.noData = true;
              item.JobRecordDetaiList = [];
              item.JobRecordDetaiHList = [];
              this.allIsRequest = false;
              this.allLoadingNum--;
            }
          });
        }
      }
    },

    sortedItems(list) {
      return list.slice().sort((a, b) => {
        const timeA = new Date(a.CreateDt);
        const timeB = new Date(b.CreateDt);

        if (timeA < timeB) {
          return 1; // a比b时间早，所以a应该排在后面
        } else if (timeA > timeB) {
          return -1; // a比b时间晚，所以a应该排在前面
        } else {
          // 如果时间相同，比较序号
          return a.JobTempletIndex - b.JobTempletIndex;
        }
      });
    },

    //获取厂区列表
    async GetWorkShopTypesAllFun() {
      let that = this;
      let res = await GetWorkShopTypesAll(10);
      if (res.Status == 10000) {
        let wtList = [];
        res.Data.map((item) => {
          wtList.push({ type: item.WSType, name: item.WSName });
        });
        that.WSTypeList = wtList;
      } else {
        that.$message.error(res.Message);
      }
    },
    //选中厂区
    handleChange(value) {
      let that = this;
      if (value) {
        that.GetSegmentsAllFun(that.searchInfo.WSType, true);
      }
    },
    //获取车间列表
    GetSegmentsAllFun: debounce(async function (WSType, ispplist = false) {
      let that = this;
      let SegSegmentID = [
        "1735FA0C-33E4-4B25-AAA2-DE084FB7D1E3",
        "5D494A1E-5F24-4036-9350-2E442A19FE87",
        "CCDB0114-7026-4218-A507-5C00E870B0B3",
        "12FF8C8D-B2DC-4554-AA9B-91703F4AB200",
      ];
      //新建单据的时候，判断类型。只显示对应类型车间
      if (!ispplist && JSON.stringify(that.selectedPPList) !== "{}") {
        switch (that.selectedPPList.OrderType) {
          case 10: //灌包
            SegSegmentID = ["5D494A1E-5F24-4036-9350-2E442A19FE87"];
            break;
          case 11: //包装
            SegSegmentID = ["1735FA0C-33E4-4B25-AAA2-DE084FB7D1E3"];
            break;
          case 12: //折叠
            SegSegmentID = ["CCDB0114-7026-4218-A507-5C00E870B0B3"];
            break;
          case 13: //冲裁
          case 14: //无纺布
          case 15: //挑选
            SegSegmentID = ["12FF8C8D-B2DC-4554-AA9B-91703F4AB200"];
            break;
          default:
            break;
        }
      }
      let res = await GetSegments({
        SegSegmentID: SegSegmentID,
        WSTypeList: WSType,
      });
      if (res.Status == 10000) {
        let wtList = [];
        res.Data.map((item) => {
          wtList.push({ type: item.SegmentID, name: item.SegmentName });
        });
        if (ispplist) {
          that.QSegmentList = wtList;
        } else {
          that.PPQSegmentList = wtList;
        }
      } else {
        that.$message.error(res.Message);
      }
    }),
    //审核状态
    getVerifyStatus(val) {
      switch (val) {
        case 0:
          return "未创建";
          break;
        case 10:
          return "已创建未填写";
          break;
        case 11:
          return "填写中";
          break;
        case 12:
          return "已填写未审核";
          break;
        case 13:
          return "已审核";
          break;
        default:
          return "未知";
          break;
      }
    },
    //滚动方法
    handleinfiniteOnLoad() {
      this.busy = true;
      setTimeout(() => {
        this.searchInfo.pageRequestModel.pageIndex += 1;
        this.getPackingPlanListFun();
      }, 1000);
    },
    /* 打印页面 */
    async onPrint(itm) {
      let isPrint = true;
      this.mateCurrentInfo.JobRecordList.forEach((item) => {
        if (item.VerifyStatus != true) {
          isPrint = false;
        }
      });

      if (!isPrint) {
        this.$message.error("批记录没有审核，请审核后再打印");
        return;
      }

      try {
        this.loading = true;
        this.$store.commit("upPrintShow", true);
        // 额外等待确保渲染完成
        await new Promise((resolve) => setTimeout(resolve, 2000));

        let list = [
          {
            AssetsID: itm.AssetsID,
            BatchNo: itm.BatchNo,
            JobGroupID: itm.JobGroupID,
            CreateDt: itm.CreateDt,
          },
        ];

        await printJobRecord(list);
        itm.PrintIndex = itm.PrintIndex + 1;

        // 触发实际打印
        this.$print(this.$refs.print);
      } catch (error) {
        this.$message.error(`打印出错: ${error.message}`);
      } finally {
        this.loading = false;
        this.$store.commit("upPrintShow", false);
      }
    },
    /* 指定打印页面 */
    async onAppointPrint() {
      let that = this;
      let isPrint = true;
      that.mateCurrentInfo.JobRecordList.forEach((item) => {
        if (item.VerifyStatus != true) {
          isPrint = false;
        }
      });

      if (!isPrint) {
        that.$message.error("批记录没有审核，请审核后再打印");
        return;
      }

      try {
        that.$store.commit("upPrintShow", true);

        let data = Object.assign([], that.mateCurrentInfo.JobRecordList);

        that.mateCurrentInfo.JobRecordList =
          that.mateCurrentInfo.JobRecordList.filter(
            (item) => item.IsPrint == true
          );

        if (
          !that.mateCurrentInfo.JobRecordList ||
          that.mateCurrentInfo.JobRecordList.length == 0
        ) {
          that.$message.error("没有配置指定打印模版");
          that.$store.commit("upPrintShow", false);
          that.mateCurrentInfo.JobRecordList = Object.assign([], data);
          return;
        }

        // 额外等待确保渲染完成
        await new Promise((resolve) => setTimeout(resolve, 2000));

        // 触发实际打印
        that.$print(that.$refs.print);

        // 等待打印完成
        while (that.startPrint) {
          await that.sleep(1000);
        }

        // 恢复原始数据
        that.mateCurrentInfo.JobRecordList = Object.assign([], data);
      } catch (error) {
        that.$message.error(`打印出错: ${error.message}`);
        that.$store.commit("upPrintShow", false);
      }
    },
    /* 一键审核 */
    onExamine(itm, val) {
      let that = this;
      this.$confirm({
        title: `审核`,
        content: `是否审核?`,
        async onOk() {
          let list = [
            {
              IsForce: val,
              AssetsID: itm.AssetsID,
              BatchNo: itm.BatchNo,
              JobGroupID: itm.JobGroupID,
              CreateDt: itm.CreateDt,
            },
          ];
          let res = await verifyJobRecord(list);
          if (!res.Data) {
            that.$message.success("审批成功");
            await that.getJobRecordToListFun(false);
            that.mateCurrentInfo.JobRecordList.forEach((item) => {
              item.VerifyStatus = true;
            });
          } else {
            that.$message.error(res.Data);
          }
        },
        onCancel() {},
      });
    },
    /* 弃审 */
    onUnExamine(itm) {
      let that = this;
      this.$confirm({
        title: `弃审`,
        content: `是否弃审?`,
        async onOk() {
          let list = [
            {
              AssetsID: itm.AssetsID,
              BatchNo: itm.BatchNo,
              JobGroupID: itm.JobGroupID,
              CreateDt: itm.CreateDt,
            },
          ];
          let res = await unVerifyJobRecord(list);
          if (!res.Data) {
            that.$message.success("弃审成功");
            await that.getJobRecordToListFun(false);
            that.mateCurrentInfo.JobRecordList.forEach((item) => {
              item.VerifyStatus = false;
            });
          } else {
            that.$message.error(res.Data);
          }
        },
        onCancel() {},
      });
    },
    /* 一键作废 */
    onInvaliDate(itm, val) {
      let that = this;
      let { JobRecordList } = this.mateCurrentInfo;
      this.$confirm({
        title: `作废`,
        content: `是否作废?`,
        async onOk() {
          let list = [
            {
              IsForce: val,
              AssetsID: itm.AssetsID,
              BatchNo: itm.BatchNo,
              JobGroupID: itm.JobGroupID,
              CreateDt: itm.CreateDt,
            },
          ];
          let res = await invaliDateJobRecord(list);
          res.Data
            ? that.$message.error(res.Data)
            : that.$message.success("作废成功");
          that.getJobRecordToListFun(false);
        },
        onCancel() {},
      });
    },
    /* 还原 */
    onUnInvaliDate(itm) {
      let that = this;
      let { JobRecordList } = this.mateCurrentInfo;
      this.$confirm({
        title: `还原`,
        content: `是否还原?`,
        async onOk() {
          let list = [
            {
              AssetsID: itm.AssetsID,
              BatchNo: itm.BatchNo,
              JobGroupID: itm.JobGroupID,
              CreateDt: itm.CreateDt,
            },
          ];
          let res = await unInvaliDateJobRecord(list);
          res.Data
            ? that.$message.error(res.Data)
            : that.$message.success("还原成功");
          that.getJobRecordToListFun(false);
        },
        onCancel() {},
      });
    },
    /* 查询列表 */
    upList() {
      this.searchInfo.pageRequestModel.pageIndex = 1;

      this.list = [];
      let { keyWords, batchNo, packingPlanNo } = this.searchInfo;
      if (keyWords != "") {
        this.searchInfo = {
          ...this.searchInfo,
          packingPlanNo: keyWords,
        };
      }
      this.getPackingPlanListFun();
      this.visible = false;
    },
    /* 单据类型筛选 */
    mateFind(type) {
      return this.mateInfo.find((item) => item.type == type);
    },
    //筛选七天时间
    onTimeChange(date, dateString) {
      this.searchInfo = {
        ...this.searchInfo,
        startDt: dateString[0],
        endDt: dateString[1],
      };
    },
    /* 确认搜索 */
    confirm() {},
    /* 修改后更新表格 */
    async upListFun() {
      if (this.mateCurrentInfo.TableType == 1) {
        this.getJobRecordDetailGroupListFun(this.mateCurrentInfo);
      } else {
        this.getJobRecordDetailListFun(this.mateCurrentInfo);
      }
    },

    /** 阻止默认事件 */
    checkChange(event) {
      event.stopPropagation();
    },

    /* 赋值工作集后查询该工作集下的批记录填写信息,批记录用 JobItemIndex字段排序 JobGroup为批记录名称 （建议填写用。隔开 暂时用。分割 */
    async checkBatch(itm, idx) {
      this.mateIdx = idx;
      this.mateCurrentInfo = itm;

      if (!itm.JobRecordList) return;
      itm.JobRecordList.map((item) => {
        if (item.TableType == 1) {
          this.getJobRecordDetailGroupListFun(item);
        } else {
          this.getJobRecordDetailListFun(item);
        }
      });
    },
    /* 切换选中工单 */
    checkPacking(item, index) {
      this.listInfo = item;
      this.currentIndex = index;
      this.mateIdx = 0;
      this.getJobRecordToListFun(true);
    },
    /* 查询工单列表  参数keyWords工单号查询   查询到有值再进行查询该工单的工作集 */
    async getPackingPlanListFun() {
      this.searchInfo.jobRecordStatusStr = this.jobRecordStatusData.join(",");
      this.searchInfo.jobGroupClass = this.jobGroupClass;
      let res = await getPackingPlanListByVerify(this.searchInfo);
      this.list = this.list.concat(res.Data.Data);
      this.listNum = res.Data.TotalNumber;
      if (this.list[0]) {
        this.mateIdx = 0;
        this.listInfo = this.list[0];
        this.currentIndex = 0;
        this.getJobRecordToListFun(true);
      } else {
        this.mateIdx = 0;
        this.mateCurrentInfo = {
          JobRecordList: [],
        };
        this.currentIndex = 0;
        this.batchList = [];
      }
      if (res.Data.Data.length == 0) {
        this.busy = true;
      } else {
        this.busy = false;
      }
    },

    /* 查询工单的批记录,传入参数选中工单的工单id 如该工单有批记录再操作查询项并通过  JobItemIndex排序*/
    async getJobRecordToListFun(val) {
      let { PackingPlanID, BatchNo } = this.listInfo;
      let res = await getJobRecordToPacking({
        PackingPlanID: PackingPlanID,
        BatchNo: BatchNo,
        JobGroupClass: this.jobGroupClass,
      });
      /* 赋值默认未选中状态 */

      res.Data.map((item) => {
        item.JobRecordList = this.sortedItems(item.JobRecordList);
      });
      res.Data.map((item) => {
        item.isCheckBox = false;
      });
      this.batchList = res.Data;

      // 新增状态判断逻辑
      if (this.batchList.length > 0) {
        const allStatuses = this.batchList.flatMap(
          (item) =>
            item.JobRecordList?.map((record) => record.JobRecordStatus) || []
        );

        if (allStatuses.length === 0) {
        } else if (allStatuses.every((s) => s === 13)) {
          this.listInfo.JobRecordStatusStr = "已审核"; // 已审核
        } else if (allStatuses.every((s) => s === 11)) {
          this.listInfo.JobRecordStatusStr = "填写中"; // 填写中
        } else if (allStatuses.every((s) => s === 10)) {
          this.listInfo.JobRecordStatusStr = "已创建未填写"; // 已创建未填写
        } else if (allStatuses.every((s) => s >= 12)) {
          this.listInfo.JobRecordStatusStr = "已填写未审核"; // 已填写未审核
        }
      }
      if (this.batchList[0]) {
        this.loading = true;
        this.mateCurrentInfo = res.Data[0];
        let { JobRecordList } = this.batchList[0];
        if (!JobRecordList || JobRecordList.length == 0) return;
        if (val) {
          this.batchNoFilter = this.searchInfo.batchNo;
          this.printStatusFilter = this.searchInfo.printStatus;
          this.isInvaliDateFilter = this.searchInfo.IsInvaliDateStatus;
        }

        // JobRecordList.sort((a, b) => a.JobTempletIndex - b.JobTempletIndex);
        // JobRecordList = this.sortedItems();

        //请求全部完成再可以操作方法 1- 先将总长度赋值
        this.loadingNum = JobRecordList.length;

        for (const item of JobRecordList) {
          //请求全部完成再可以操作方法 2- 将请求可控为true
          this.isRequest = true;
          if (this.isRequest) {
            if (item.TableType == 1) {
              this.getJobRecordDetailGroupListFun(item);
            } else {
              this.getJobRecordDetailListFun(item);
            }
          }
        }
      } else {
        this.loading = false;
        this.mateCurrentInfo = {
          JobRecordList: [],
        };
        this.batchList = [];
      }
    },

    /* 查询工作集对应的批记录项  传入工作集id JobRecordID 用于单例列表*/
    async getJobRecordDetailGroupListFun(val) {
      try {
        //请求全部完成再可以操作方法 3- 先控制停止循环
        this.isRequest = false;
        let params = {
          JobRecordID: val.JobRecordID,
          CreateDt: val.CreateDt,
          BatchNo: val.BatchNo,
        };
        let res = await getJobRecordDetailGroups(params);

        if (!res.Success) {
          let { JobRecordList } = this.mateCurrentInfo;
          JobRecordList.forEach((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              item.noData = true;
              item.JobRecordDetaiList = [];
              this.isRequest = false;
              this.loadingNum--;
            }
          });
          return;
        }
        let list = res.Data.sort((a, b) => a.JobItemIndex - b.JobItemIndex);
        list.forEach((item) => {
          item.JobGroup = item.JobGroup.split("。");
          item.JobRecordDetailList = item.JobRecordDetailList.sort(
            (a, b) => a.JobItemIndex - b.JobItemIndex
          );
        });

        if (this.batchList[this.mateIdx]) {
          if (this.batchList[this.mateIdx].JobRecordList.length == 0) return;
          let { JobRecordList } = this.mateCurrentInfo;
          JobRecordList.forEach((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              if (list.length === 0) {
                item.noData = true;
                item.JobRecordDetaiList = [];
              } else {
                item.JobRecordDetaiList = list;
              }

              this.isRequest = false;
              this.loadingNum--;
            }
          });
        }
      } catch (err) {
        if (this.batchList[this.mateIdx]) {
          if (this.batchList[this.mateIdx].JobRecordList.length == 0) return;
          let { JobRecordList } = this.mateCurrentInfo;
          JobRecordList.forEach((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              item.noData = true;
              item.JobRecordDetaiList = [];
              this.isRequest = false;
              this.loadingNum--;
            }
          });
        }
      }
    },
    /* 查询工作集对应的批记录项  传入工作集id JobRecordID 用于聚合列表*/
    async getJobRecordDetailListFun(val) {
      try {
        this.isRequest = false;
        let params = {
          JobRecordID: val.JobRecordID,
          CreateDt: val.CreateDt,
          BatchNo: val.BatchNo,
        };
        let res = await getJobRecordDetails(params);

        if (!res.Success) {
          let { JobRecordList } = this.mateCurrentInfo;
          JobRecordList.map((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              item.noData = true;
              item.JobRecordDetaiList = [];
              item.JobRecordDetaiHList = [];
              this.isRequest = false;
              this.loadingNum--;
            }
          });
          return;
        }
        let stagingHeader = res.Data.filter(
          (item) => item.JobRecordDetailIndex == 1
        );

        stagingHeader = stagingHeader.sort((a, b) => {
          return a.JobItemIndex - b.JobItemIndex;
        });
        let polyHeaderList = polymerizeTitle.handleTitleList(stagingHeader);
        /* 先根据 JobRecordDetailIndex 把每一项排序 */
        let stagingBatchDetailList = res.Data.sort((a, b) => {
          return a.JobRecordDetailIndex - b.JobRecordDetailIndex;
        });
        /* 通过 pop方法获取数组最后一位确定共几行 */
        let batchDetailNum =
          stagingBatchDetailList[stagingBatchDetailList.length - 1]
            .JobRecordDetailIndex;
        /* 定义一个空数组 */
        let detailList = [];

        /* 通过遍历获取最大值添加列表中相对应的JobRecordDetailIndex项为一行 push进detailList数组 */
        for (let index = 1; index <= batchDetailNum; index++) {
          let list = stagingBatchDetailList.filter(
            (fitm) => fitm.JobRecordDetailIndex == index
          );
          detailList.push(list);
        }

        /* 遍历结束后将子项排序后赋值 */
        let detaiArray = detailList.map((ditm) => {
          ditm.sort((a, b) => {
            return a.JobItemIndex - b.JobItemIndex;
          });
          ditm = polymerizeTitle.handleTitleList(ditm);
          return ditm;
        });

        if (this.batchList[this.mateIdx]) {
          if (this.batchList[this.mateIdx].JobRecordList.length == 0) return;
          let { JobRecordList } = this.mateCurrentInfo;
          JobRecordList.map((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              if (detaiArray.length == 0) {
                item.noData = true;
              }
              item.JobRecordDetaiList = detaiArray;
              item.JobRecordDetaiHList = polyHeaderList;
              this.isRequest = false;
              this.loadingNum--;
            }
          });
        }
      } catch (err) {
        if (this.batchList[this.mateIdx]) {
          if (this.batchList[this.mateIdx].JobRecordList.length == 0) return;
          let { JobRecordList } = this.mateCurrentInfo;
          JobRecordList.map((item, index) => {
            if (item.JobRecordID == val.JobRecordID) {
              item.noData = true;
              item.JobRecordDetaiList = [];
              item.JobRecordDetaiHList = [];
              this.isRequest = false;
              this.loadingNum--;
            }
          });
        }
      }
    },
    /* 批量审核 */
    batchExamine() {
      let that = this;
      let list = this.batchList.filter((item) => item.isCheckBox);

      if (list.length == 0)
        return this.$message.error("请先选中项再操作一键审核");

      this.$confirm({
        title: `批量审核`,
        content: `确定要审核选中的${list.length}条记录吗?`,
        async onOk() {
          try {
            that.loading = true;
            let successCount = 0;
            let errorCount = 0;

            // 使用Promise.all确保所有异步操作完成
            await Promise.all(
              list.map(async (item) => {
                try {
                  if (item.JobRecordList && item.JobRecordList.length > 0) {
                    let verifyList = [
                      {
                        IsForce: false,
                        AssetsID: item.JobRecordList[0].AssetsID,
                        BatchNo: item.JobRecordList[0].BatchNo,
                        JobGroupID: item.JobRecordList[0].JobGroupID,
                        CreateDt: item.JobRecordList[0].CreateDt,
                      },
                    ];

                    let res = await verifyJobRecord(verifyList);
                    if (res.Status == 10000) {
                      if (res.Data && res.Data != "") {
                        that.$message.error(res.Data);
                        errorCount++;
                      } else {
                        successCount++;
                      }
                    } else {
                      errorCount++;
                    }
                  }
                } catch (error) {
                  that.$message.error(`审核失败: ${error.message || error}`);
                  errorCount++;
                }
              })
            );

            if (successCount > 0) {
              that.$message.success(`成功审核${successCount}条记录`);
              that.getJobRecordToListFun(false);
            }
            if (errorCount > 0) {
              that.$message.error(`${errorCount}条记录审核失败`);
            }
          } catch (error) {
            that.$message.error(`批量审核出错: ${error.message || error}`);
          } finally {
            that.loading = false;
          }
        },
        onCancel() {},
      });
    },
  },
  mounted() {
    this.defaultdateList = [
      moment().subtract(6, "days").format("YYYY-MM-DD"),
      moment().format("YYYY-MM-DD"),
    ];
    this.searchInfo = {
      ...this.searchInfo,
      startDt: this.defaultdateList[0],
      endDt: this.defaultdateList[1],
    };
    this.getPackingPlanListFun();
    this.GetWorkShopTypesAllFun();
  },
};
</script>

<style lang="less" scoped>
.ant-spin-spinning {
  position: absolute;
  top: calc(50% - 100px);
  left: 50%;
  z-index: 2000;
  color: blue;
}

/deep/.ant-spin-nested-loading {
  height: 100%;
}

/deep/.ant-spin-container {
  height: 100%;
}

.spin-box-div {
  height: 100%;
  display: flex;
  flex-direction: column;
}

//旋转图标颜色
.ant-spin-lg .ant-spin-dot i {
  // background: #fff;
  background: blue;
}

.ant-spin-text {
  color: blue;
}

/deep/.ant-drawer-body {
  padding: 10px;
}

.table-margin {
  margin-bottom: 0.625rem;
}

.currency-box {
  position: relative;

  .section-box-info {
    p {
      margin: 0;
    }
  }
}

.article-list-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  width: 28rem;
  .article-top {
    flex: 1;
    transition: max-height 0.3s ease;
    overflow: hidden;
  }
}

.batch-printing-right {
  display: flex;
  flex-direction: column;
  width: 0;
  .header-title {
    display: flex;
  }
  header {
    display: flex;
    padding-bottom: 0.6rem;
    border-bottom: 2px solid #f0f2f5;

    .batch-left {
      flex: 1;
      display: flex;
      overflow-x: auto;
    }
    .batch-right {
    }
    .type-list-box {
      display: flex;
      flex-direction: column;
      position: relative;
      cursor: pointer;
      flex: 0 0 25%;
      background: #f0ebeb;
      padding: 0.3125rem;
      border-radius: 0.3125rem;
      margin-right: 0.3125rem;

      .info-box {
        display: flex;
        margin: 0.3rem;
        span:nth-child(3) {
          flex: 2;
        }

        span:nth-child(4) {
          flex: 4;
        }
      }
      .info-box-handle {
        display: flex;
        flex-direction: column;
        margin: 0.3rem;
        span:nth-child(3) {
          flex: 2;
        }

        span:nth-child(4) {
          flex: 4;
        }
      }
    }
  }

  section {
    flex: 1;
    overflow: auto;
  }
}

.batch-check-box {
  display: flex;
  justify-content: flex-end;
}

.print-inside {
  page-break-inside: avoid;
}

.active {
  background-color: #dcf0ef !important;
}
.watermark {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-30deg);
  font-size: 32px;
  color: rgba(0, 128, 0, 0.3); /* 绿色半透明 */
  z-index: 1;
  pointer-events: none; /* 防止水印阻挡用户交互 */
}
</style>
<style media="print">
@media print {
  @page {
    margin: 5mm 10mm 15mm 10mm;
    size: A4 landscape;
    color: #000000 !important;
    /* 在底部居中显示页码 */
    @bottom-center {
      content: counter(page) "/" counter(pages);
    }
  }

  tfoot {
    display: table-footer-group;
  }

  .batch-thead {
    width: 100% !important;
    display: block !important;
  }

  .thead-box {
    display: block !important;
  }

  .table-name {
    width: 100% !important;
    display: block !important;
  }

  .table-name .table-name-td {
    width: 100% !important;
    text-align: center !important;
  }

  .print-box {
    page-break-after: always !important;
  }

  .header-show,
  .header-space,
  .footer,
  .footer-space {
    display: block !important;
  }
}
</style>
